package com.spc.car.web.controller.publish;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.spc.car.common.exception.CustomException;
import com.spc.car.common.lang.UUID;
import com.spc.car.common.utils.StringUtils;
import com.spc.car.core.framework.web.domain.AjaxResult;
import com.spc.car.data.domain.htgg.po.HtggPublishPO;
import com.spc.car.data.domain.htgg.vo.HtggPublishDataVO;
import com.spc.car.data.domain.htgg.vo.ProjectHtggPublishEditVO;
import com.spc.car.data.domain.htgg.vo.ProjectHtggPublishVO;
import com.spc.car.data.domain.htgg.xml.ContractAttachList;
import com.spc.car.data.domain.htgg.xml.ContractPublishList;
import com.spc.car.data.domain.htgg.xml.node.ContractAttach;
import com.spc.car.data.domain.htgg.xml.node.ContractPublish;
import com.spc.car.data.entity.project.ProjectHtggPublish;
import com.spc.car.data.entity.project.ProjectHtggPublishAttach;
import com.spc.car.data.service.project.ProjectHtggPublishAttachService;
import com.spc.car.data.service.project.ProjectHtggPublishService;
import com.spc.car.service.util.JacksonXmlUtils;
import com.spc.car.service.util.WebserviceClientUtil;
import com.spc.car.web.config.WsdlConfig;
import com.spc.car.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

@Api(tags = "合同公告发布")
@Validated
@Slf4j
@RestController
@RequestMapping("/htgg")
public class HtggPublishController extends BaseController {

    @Value("${oa.attach.url}")
    private String filePtah;

    @Autowired
    WsdlConfig wsdlConfig;

    @Autowired
    ProjectHtggPublishService htggPublishService;

    @Autowired
    ProjectHtggPublishAttachService htggPublishAttachService;

    @ApiOperation(value = "上传附件", notes = "上传合同公告附件信息")
    @PostMapping("/uploadHtggAttach")
    public AjaxResult uploadHtggAttach(MultipartFile multipartFile,
                                       @RequestParam(name = "contractUuid", required = true) String contractUuid,
                                       HttpServletRequest request) throws Exception {
        if (multipartFile.isEmpty()) {
            throw new CustomException("上传的附件不能为空！");
        }

        String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf(".") + 1);
        List<String> exist = Lists.newArrayList("doc", "docx", "pdf", "wps");
        if (!exist.contains(fileType)) {
            return AjaxResult.error("上传附件格式有误，附件格式为：.doc, .docx, .pdf, .wps");
        }

        htggPublishAttachService.upload(multipartFile, filePtah + "/htgg",contractUuid, getPrintUser());
        return AjaxResult.success("附件保存成功");
    }

    @ApiOperation(value = "保存", notes = "保存合同公告待发布数据")
    @PostMapping("/save")
    public AjaxResult save(@Valid @RequestBody ProjectHtggPublishVO projectHtggPublishVO) {

        projectHtggPublishVO.setOperatorId(getPrintUser().getUserId());
        projectHtggPublishVO.setOperatorName(getPrintUser().getUserName());
        projectHtggPublishVO.setUuid(UUID.fastUUID().toString());
        htggPublishService.add(projectHtggPublishVO);

        AjaxResult ajaxResult = AjaxResult.success("保存成功！");
        ajaxResult.put("contractUUID", projectHtggPublishVO.getUuid());
        return ajaxResult;
    }

    @ApiOperation(value = "编辑", notes = "编辑合同公告待发布数据")
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody ProjectHtggPublishEditVO publishEditVO) {
        publishEditVO.setOperatorId(getPrintUser().getUserId());
        publishEditVO.setOperatorName(getPrintUser().getUserName());
        htggPublishService.edit(publishEditVO);

        return AjaxResult.success("编辑成功！");
    }

    @ApiOperation(value = "获取合同公告发布信息", notes = "获取合同公告发布信息")
    @PostMapping("/getHtggPublishInfo")
    public AjaxResult getHtggPublishInfo(@RequestParam(name = "contractUUID", required = true) String contractUUID) {

        ProjectHtggPublish htggPublish = htggPublishService.getOne(new LambdaQueryWrapper<ProjectHtggPublish>()
                .eq(ProjectHtggPublish::getUuid, contractUUID));

        List<ProjectHtggPublishAttach> attachList = htggPublishAttachService.list(new LambdaQueryWrapper<ProjectHtggPublishAttach>()
                .eq(ProjectHtggPublishAttach::getContractUuid, contractUUID));

        AjaxResult ajaxResult = AjaxResult.success("查询成功！");
        ajaxResult.put("htggPublishData", htggPublish);
        ajaxResult.put("attachData", attachList);
        return ajaxResult;
    }

    @ApiOperation(value = "合同公告数据列表", notes = "获取合同公告数据列表")
    @PostMapping("/listProjectHtggPublist")
    public AjaxResult listProjectHtggPublist(@Valid @RequestBody HtggPublishPO htggPublishPO) {
        Page<ProjectHtggPublish> page = htggPublishService.page(htggPublishPO.getPage(), htggPublishPO.towWrapper());
        return AjaxResult.success("查询成功！", page);
    }

    @ApiOperation(value = "发布合同公告数据", notes = "发布合同公告数据")
    @PostMapping("/publish")
    public AjaxResult publish(@Valid @RequestBody HtggPublishDataVO publishDataVO) throws Exception {

        if (!CollectionUtils.isEmpty(publishDataVO.getContractUUID())) {
            List<ContractPublish> contractPublishList = new ArrayList<>();
            List<ContractAttach> contractAttachList = new ArrayList<>();
            for (String contractUUID : publishDataVO.getContractUUID()) {
                ContractPublish contractPublish =
                        htggPublishService.getHtggInfo(contractUUID);
                contractPublish.setUserId("91530100738085426B");
                contractPublish.setUserName(publishDataVO.getUserName());
                contractPublishList.add(contractPublish);

                contractAttachList = htggPublishAttachService.listAttachByContractUuid(contractUUID);
            }

            ContractPublishList publishList = new ContractPublishList();
            publishList.setContractPublishes(contractPublishList);
            String xmlParams = JacksonXmlUtils.beanToXml(publishList);

            //获取附件信息
            if (CollectionUtils.isEmpty(contractAttachList)) {
                return AjaxResult.error("合同公告附件节点不能为空！");
            }

            ContractAttachList attachList = new ContractAttachList();
            attachList.setAttachs(contractAttachList);
            String xmlAttachParams = JacksonXmlUtils.beanToXml(attachList);

            String xmlData = StringUtils.join("<BODY>", xmlParams, xmlAttachParams, "</BODY>");
            String result = WebserviceClientUtil.publishData(wsdlConfig.getWsdlurl(), wsdlConfig.getMethods(), xmlData);

            log.info("请求的XML参数>>{}", xmlData);
            AjaxResult ajaxResult = AjaxResult.success();
            ajaxResult.put("retMsg", JSON.parse(result.replace("\\", "")));
            return ajaxResult;
        }

       return AjaxResult.error("发布数据有误！");
    }

    @ApiOperation(value = "设置发布状态", notes = "设置合同公告数据发布状态，发布成功后更改")
    @PostMapping("/changePublishStatus")
    public AjaxResult changePublishStatus(@RequestParam(name = "contractUUID", required = true) String contractUUID) {
        htggPublishService.update(new LambdaUpdateWrapper<ProjectHtggPublish>()
                .eq(ProjectHtggPublish::getUuid, contractUUID)
                .set(ProjectHtggPublish::getPublishStatus, "P"));
        return AjaxResult.success("状态设置成功！");
    }
}
